import axios from 'axios'
import {
    message
} from "ant-design-vue"


const service = axios.create({
    baseURL: "", // url拼接，鉴于目前系统存在多个地址，该参数设为空或者不写
    withCredentials: false, // 发送请求的时候是否携带cookie
    timeout: 60000 // 请求超时时间 单位毫秒
})


const times = 1.5 //单位秒，ajax取消延后时间
const pending = []; //声明一个数组用于存储每个请求的取消函数和axios标识

let cancelToken = axios.CancelToken;
let removePending = (config) => {
    // console.log(new Date().getTime()-pending[pending.length - 2].t)
    if (pending.length > 1 && pending[pending.length - 2].u === config.url + paramsStr(config.data || config.params) && pending[pending.length - 1].t - pending[pending.length - 2].t < times * 1000) {
        console.log("ajax取消操作")
        pending[pending.length - 1].f(); //执行取消操作
        pending.splice(pending.length, 1);
    }
}

const paramsStr = params => {
    let str = "";
    if (typeof params === "undefined") {
        str = ""
    } else if (typeof params === "object") {
        Object.keys(params).forEach(key => {
            const element = params[key];
            if (element || element == 0) {
                if (str) {
                    str += `&${key}=${element}`;
                } else {
                    str += `?${key}=${element}`;
                }
            }
        });
    } else {
        str = `?${params}`;
    }
    return str;
}


// 添加请求拦截器
service.interceptors.request.use(function (config) {
    config.cancelToken = new cancelToken((c) => {
        // 用请求地址&请求参数拼接的字符串
        pending.push({
            u: config.url + paramsStr(config.data || config.params),
            t: new Date().getTime(),
            f: c
        });
    });
    removePending(config)
    return config;
}, function (error) {
    return Promise.reject(error);
});

/**
 * 响应请求的拦截器
 */
service.interceptors.response.use(data => {
        const {
            code,
            msg
        } = data
        if (code === 200) return data
        if (code === 401) message.error('Missing Token~')
        else if (code === 403) message.error('此接口无访问权限~');
        else message.error(msg ? msg : '接口调用失败~');
        return message.reject(data)
    },
    reject => {
        message.error('请求失败~');
        return Promise.reject(reject)
    }
)

/**
 * 添加 XS-AUTH-TOKEN 到 headers
 * @param configObj
 */
function headerToken(configObj) {
    //如果有 XS-AUTH-REQ 或者 XS-AUTH-TOKEN
    if (configObj.headers['XS-AUTH-REQ']) return configObj
    if (configObj.headers['XS-AUTH-TOKEN']) return configObj
    //判断是否有 initialHeaderBaseStr
    const initialHeaderBaseStr = sessionStorage.getItem("initialHeaderBaseStr")
    if (initialHeaderBaseStr) configObj.headers['XS-AUTH-TOKEN'] = initialHeaderBaseStr
    return configObj
}



/**
 * @description:  axios get 请求
 * @param {*} url   接口请求提示
 * @param {*} params   接口请求参数
 * @param {*} configObj   配置参数
 * @return {*}  返回接口参数
 */

export function axiosPost(url, params, configObj = {
    headers: {}
}) {

    return new Promise((resolve, reject) => {
        service.post(url, params, headerToken(configObj))
            .then(resolve, reject)
            .catch(reject)
    })
}


/**
 * @description:  axios get 请求
 * @param {*} url   接口请求提示
 * @par {*} configObj   配置参数am
 * @return {*}  返回接口参数
 */
export function axiosgGet(url, configObj) {
    return new Promise((resolve, reject) => {
        service.get(url, headerToken(configObj))
            .then(resolve, reject)
            .catch(reject)
    })
}


/**
 * @description:  axios get 请求
 * @param {*} url   接口请求提示
 * @param {*} params   配置参数
 * @param {*} name   下载文件名称
 * @return {*}  返回接口参数
 */
export function downloadFile(url, params, name = 'fileName', configObj = {
    headers: {
        responseType: 'blob'
    }
}, type) {
    service.post(url, params, {
        responseType: 'blob'
    }, headerToken(configObj, type)).then(res => {
        let blob = res.data
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = name + `.xlsx`
            a.href = e.target.result
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        }
    })

}


export default service